<?php
App::import('Vendor', 'fpdf', true, array(), 'fpdf' . DS . 'fpdf.php');

//App::import('Vendor', 'fpdf');
//App::import('Vendor', 'fpdf/fpdf.php');
//App::uses('fpdf', 'Vendor');

if (!defined('PARAGRAPH_STRING')) define('PARAGRAPH_STRING', '~~~');

class FpdfHelper extends FPDF {
	var $subcabecalho;
	var $sub_titulo;
	var $imprimeCabecalho = true;
	var $imprimeRodape = true;
	var $tablewidths;
	var $tablealigns;
	var $footerset;
	var $maxHeader;
	var $footerPage;
	var $headerPage;
	var $xStart;
	var $cellSubTitulo = true;

	var $numberFooter = 1;
	var $useNumberFooter = false;
	
	var $tabletitles;
    var $tabletitlesfont;
    var $tabletitlesheight;
    var $tabletitlesborder;	
    var $tabletitlesalign;
    var $tabletitleswidths;        
	var $breaksOptions;
	var $breaksFilters;
	var $breaksGroup;
	var $breaksPrints;
	var $breakItemControl;
 	var $breakItemTitles;
 	var $breakItemColuns;	
 	var $breakWidthLabel = 25;
 	var $breakBorderLabel = 0;
 	var $maxNumberLines;
 	var $minNumberLines;
	var $positionMaxLine;	
	var $positionMaxPage;	
	var $breakItemTotals;
	var $breakGroupTotals;
	var $noBreakGroupTotals = array();
	var $tamCellTotal = 0;
	var $dataSet;
	var $printZeros = false;
	var $printTotalsItems = true;
	var $lineTotals;
	var $breaksSubtitles;
	var $printBreaksGroups = true;
	var $haveBreak;
	
	var $breakItemDetailsLabel;
	var $breakItemDetails;
	var $breakItemDetailsColums;
	var $breakItemDetailsAlings;
	var $breakItemDetailsTypes;
	var $breakItemLine;
	var $breakItemOperation;
	var $breakItemValues;
	var $lineTotalsDual;
	var $breakTotalItemOperations;
	

	var $breakTotalItemLabels;
 	var $breakTotalItemFields;
 	var $breakTotalItemColums;
 	var $breakTotalItemAlings;
 	var $breakTotalItemTypes;
 	
 	var $hideItemControl = false;
 	var $printTotalGroups = false;
 	var $printTotalGeral = true;
 	var $breakTotalFields;		
 	
    var $breakTotalLabels;
    var $breakTotalColums;
    var $breakTotalAlings;
    var $breakTotalTypes;
    var $breakTotalOperations;
    var $noBreakTotalLabels;
    var $spaceGroupTop = true; //era true em 09/11/09
	var $spaceGroupBotton = true;//era true em 09/11/09
	var $spaceGeral = 0;
	
	var $operationsTotalItem;
	var $labelItemOperation = null;
	var $decimalItemOperation = 'valor';
	var $tablestyles = array();
	var $labelsTotal = array();

	var $detailFormat = true;
	var $operationItem = array();
	var $operacaoTotalItem = array();
	var $removeIncrementoItem = array();
	
 
    function setup ($orientation='P',$unit='mm',$format='A4') {
        $this->FPDF($orientation, $unit, $format);
    }

    function fpdfOutput ($name = 'page.pdf', $destination = 's') {
        return $this->Output($name, $destination);
    }

  
    function Header(){
    	
    	//exita formatar cabe�alho
      $tablestyles = $this->tablestyles;	
      $this->tablestyles = array();
      
      $this->AliasNbPages();
 	  //pega dados da fonte antes de imprimir o cabe�alho
	  $family=$this->FontFamily;
	  $style=$this->FontStyle.($this->underline ? 'U' : '');
	  $size=$this->FontSizePt;
	  	//teste de impress�o de cabe�alho e n�o reimpress�o caso ja tenha sido impresso
       	if ($this->imprimeCabecalho && !isset($this->headerPage[$this->page])){
       		//cria �ndice com n�mero da p�gia atual na array para n�o ser impressa novamente
       		$this->headerPage[$this->page]=$this->page;

       		//pega dados do cliente no controller clientes/cabe�alho
       		//$poderpublico_id = $_SESSION['Login']['Cliente']['Orgao']['poderpublico_id'];
       	//	$dataPoderPublico = $this->Orgao->Poderpublico->read(null, $poderpublico_id);
       		//$esferaadministrativa_id = $_SESSION['Login']['Cliente']['Orgao']['esferaadministrativa_id'];
       		//$dataEsferaAdministrativa = $this->Orgao->Esferaadministrativa->read(null, $esferaadministrativa_id);
       		//$orgao=$_SESSION['Login']['Cliente']['Orgao']['sigla_orgao'].' - '.$_SESSION['Login']['Cliente']['Orgao']['orgao'].' - '.$dataEsferaAdministrativa["Esferaadministrativa"]["esfera_administrativa"];
       		
       		$cabecalho=array(
       				'poderpublico_sigla'=>UFAM,
       				'poderpublico'=>"Universidade Federal do Amazonas",
       				'imagem_esquerda'=>"logoufam.jpg",
       				'imagem_direita'=>null,
       				
       				'sistema'=>"SIDEP - Sistema de Deprecia��o")   ;
			 
            if(isset($cabecalho)){
            //	$this->y=3;
            	$this->y = 7;
                if ($this->CurOrientation == 'P') {
            		$lnTam = 190;
        		} else {
            		$lnTam = 280;
        		}
		        //Title
		      
		           $this->Ln(0.5);
		        $this->Cell(0,0,'',1,0,'C');
		        $this->Ln(0.5);
		        $this->Cell(0,0,'',1,0,'C');
		        $this->Ln(0.5);
		        $this->SetFont('Arial','B',10);
		        // Imprime brasao
		      /*  $this->Image(WWW_ROOT.'img/'.$cabecalho['imagem_esquerda'],11,11,9);
		        // Imprime logo do estado
		        $this->Image(WWW_ROOT.'img/'.$cabecalho['imagem_direita'],$this->w - 22,11,15);
		        $this->Cell(0,5,$cabecalho['poderpublico'],0,0,'C');
		        $this->Ln(4);*/
		        if(isset($cabecalho)){
		        	if(isset($cabecalho['imagem_esquerda']) && !empty($cabecalho['imagem_esquerda']))
		        	$this->Image(WWW_ROOT.'img/'.$cabecalho['imagem_esquerda'],9,10,0,13);
			        // Imprime logo do estado
			        if(isset($cabecalho['imagem_direita']) && !empty($cabecalho['imagem_direita']))
			        $this->Image(WWW_ROOT.'img/'.$cabecalho['imagem_direita'],$this->w - 26,10,0,13);
			        $this->Cell(0,5,$cabecalho['poderpublico'],0,0,'C');
			        $this->Ln(4);
		            $this->SetFont('Arial','',12);
		           // $this->Cell(0,5,$cabecalho['cliente_sigla'].' - '.$cabecalho['cliente'],0,1,'C');
		            $this->Cell(0,5,$cabecalho['sistema'],0,1,'C');
		   		}
		   		
		      //    $this->SetY(7);
		        $this->Cell(0,0,'',1,0,'C');
		        $this->Ln(0.5);
		        $this->Cell(0,0,'',1,1,'C');
		         $this->SetX($this->w-47);
		   		 $this->SetFont('Arial','I',8);
		          $this->Cell(45,4,'Impresso em:'.date('d/m/Y H:i:s'),0,1,'R');
		       // $this->Ln(5);
      		}
	       	//pega os parametros da array para montar um subcabe�alho
            if(isset($this->subcabecalho)){
              	$sub_cabecalho = $this->requestAction($this->subcabecalho);
            }
            if(isset($sub_cabecalho)){
                $this->Linha($sub_cabecalho);
                $this->ln(5);
            }
            //pega os parametros da array para montar um subtitulo
            if(!empty($this->sub_titulo)){
               $this->Linha($this->sub_titulo);
            }
                   
            //imprime cabe�alho com muticelsinline
            if(!empty($this->tabletitles)){
				$conteudos=null;
				$conteudos[] = $this->tabletitles;
				$this->Ln(3);
				if(!$this->tabletitlesfont)
				{
					$fontTitle = array(0=>array('font'=>array ('font'=>'Arial','destaque'=>'','tamanho'=>'8')));
				}
				else
				{
					$fontTitle = array(0=>array('font'=>$this->tabletitlesfont));
				}
				//pega dados da fonte
		        $family=$this->FontFamily;
				$style=$this->FontStyle.($this->underline ? 'U' : '');
				$size=$this->FontSizePt;
				$this->Linha($fontTitle);
            	if($this->tabletitlesaligns)
				{
					 $this->tablealigns = $this->tabletitlesaligns;
					 $alinhamentoAnt = $this->tabletitlesaligns;
				}
				if($this->tablealigns)
				{
				 	$alinhamentoAnt = $this->tablealigns; 
				}			
				if(!$this->tabletitlesheight)
				{
					$this->tabletitlesheight = 5;
				}
				if(!$this->tabletitlesborder)
				{
					$this->tabletitlesborder = 0;
				}
				if($this->tabletitleswidths)
				{
				 	$this->tablewidths = $this->tabletitleswidths;
				}								
				$this->MultiCellsInLine($conteudos, $this->tabletitlesheight, $this->tabletitlesborder);
	
			    $this->tablealigns = $alinhamentoAnt; // recupera alinhamento dos items
	              //seta a fonte usada antes do rodap�
	       		$this->SetFont($family,$style,$size);
	       		//Imprime linha dupla
	       		$this->Cell(0,1,null,'BT',1,'C');
	       		$this->Ln(1);
             }            
             
             if(!empty($this->breaksSubtitles))
             {           	
             	$family=$this->FontFamily;
				$style=$this->FontStyle.($this->underline ? 'U' : '');
				$size=$this->FontSizePt;
				
				foreach($this->breaksSubtitles as $valueSub)
				{				
					if (isset($valueSub['margin']) and !empty($valueSub['margin'])){
						$margin = $this->breakWidthLabel + $valueSub['margin'];	
					} else $margin = $this->breakWidthLabel;
					$this->SetFont('Arial','',10);
					$this->Cell($margin,$valueSub['height'],$valueSub['label'],$this->breakBorderLabel,0,'R');
					$this->SetFont('Arial','B',10);									
					$this->MultiCell(0,$valueSub['height'],$valueSub['value'],$this->breakBorderLabel,'L');
					$this->SetFont('Arial','',8);					
				}	
								
				$this->SetFont($family,$style,$size);          	
             }

          
            

         }
         //seta altura do cabe�alho para a margem superior
         $this->maxHeader=$this->GetY();
         //seta a fonte usada antes do cabe�alho
         $this->SetFont($family,$style,$size);
         $this->tablestyles=$tablestyles;
      }   
    
    

    function Footer() {
    	//pega dados da fonte em uso antes do rodap�
        $family=$this->FontFamily;
		$style=$this->FontStyle.($this->underline ? 'U' : '');
		$size=$this->FontSizePt;

		//teste de impress�o de rodap� e n�o reimpress�o caso ja tenha sido impresso
		if ($this->imprimeRodape && !isset($this->footerPage[$this->page])){
		//cria �ndice com n�mero da p�gia atual na array para n�o ser impressa novamente
		$this->footerPage[$this->page]=$this->page;
        // Pega parametros da p�gina
        if ($this->CurOrientation == 'P') {
            $lnTam = 190;
        } else {
            $lnTam = 280;
        }
        //Position at 1.5 cm from bottom
        $this->SetY(-10);
        //Arial italic 8
		$this->SetFont('Arial','I',8);
        //Page number
        $this->Cell(0,0,'',1,0,'C');
        $this->Ln(0.5);
        $this->Cell(0,0,'',1,0,'C');
        $this->Ln(0.5);
      //  $this->Cell(60,10,'Impresso em: '.date('d/m/Y H:i:s'),0,0,'L');
          $this->Cell(60,10," ",0,0,'L');

        // controle manual/autom�tico de numera��o de p�gina
		if(!$this->useNumberFooter){
       		 $this->Cell(($lnTam / 2),5,'Pag. '.$this->PageNo()."/{nb}",0,0,'C');
		}
		else{
			$this->Cell(($lnTam / 2),5,"P�gina {$this->numberFooter}",0,0,'C');
			$this->numberFooter++;
		}
      }
      //seta a fonte usada antes do rodap�
       $this->SetFont($family,$style,$size);
    }

    function Linha($dados){
              if(isset($dados) && is_array($dados) && count($dados)){
                $max_y=$this->GetY();
                foreach($dados as $sub_texto)	{
                	if(is_array($sub_texto) && count($sub_texto))
                	{
                		if(isset($sub_texto['posicao']['x'])){
                			$this->SetX($sub_texto['posicao']['x']);
                		}
                	    if(isset($sub_texto['posicao']['y'])){
                			$this->SetY($sub_texto['posicao']['y']);
                		}
                		  if(isset($sub_texto['font']['font'])){
               		  		$this->SetFont($sub_texto['font']['font'],$sub_texto['font']['destaque'],$sub_texto['font']['tamanho']);
                		  }

                		  // imprime quadro no cabe�calho
                		  if(isset($sub_texto['quadro'])){
                		   	  $this->Cell($sub_texto['quadro']['x'],$sub_texto['quadro']['y'],null,'1',$sub_texto['quadro']['ln'],'C');
                		  	
                		  }
                		  if(isset($sub_texto['celula']))
                		  {	  	
	                		  if($this->cellSubTitulo==true){// imprime  com celulas
	               		 		 $this->Cell($sub_texto['celula']['x'],$sub_texto['celula']['y'],$sub_texto['celula']['texto'],$sub_texto['celula']['borda'],$sub_texto['celula']['ln'],$sub_texto['celula']['alinhamento']);
	                		  }else{//imprime com multicels
	                		  	$y_anterior=$this->GetY();
	                		  	$x_anterior=$this->GetX();
	                		  	$this->MultiCell($sub_texto['celula']['x'],$sub_texto['celula']['y'],$sub_texto['celula']['texto'],$sub_texto['celula']['borda'],$sub_texto['celula']['alinhamento']);

	                		   	if($max_y<$this->GetY()){
	                		  		$max_y=$this->GetY();
	                		  	}

	 							if($sub_texto['celula']['ln']==0){// sem quebra de linha
	 								$x_anterior+=$sub_texto['celula']['x'];
	 								$this->SetXY($x_anterior,$y_anterior);
	 							}else{
	 								$this->SetY($max_y);
	 						   }
	                	    }           	    
	                	    
                	     }
                	    
                	    
                	    
                	    
                	}
                 }
              }
    }

    function getCurPage(){
		return $this->page;
	}

    function requestAction($url, $extra = array()) {
		if (!empty($url)) {
			$dispatcher =& new Dispatcher();
			if(isset($this->plugin)){
				$extra['plugin'] = $this->plugin;
			}
			if (in_array('return', $extra)) {
				$extra['return'] = 0;
				$extra['bare'] = 1;
				$extra['requested'] = 1;
				ob_start();
				$out = $dispatcher->dispatch($url, $extra);
				$out = ob_get_clean();
				return $out;
			} else {
				$extra['return'] = 1;
				$extra['bare'] = 1;
				$extra['requested'] = 1;
				return $dispatcher->dispatch($url, $extra);
			}
		} else {
			return false;
		}
	}

	function tablecontents($datas,$lineheight=5,$border=0,$align='J') {
		$this->MultiCellsInLine($datas,$lineheight,$border,$align);
	}

	function MultiCellsInLine($datas,$lineheight=5,$border=0,$align='J',$retornaLinha=false) {



		$l = $this->lMargin;

		$startheight = $h = $this->GetY();
		$startpage = $currpage = $maxpage = $this->page;

		foreach($this->tablewidths AS $width) {
			if(!isset($fullwidth))$fullwidth=0;
			$fullwidth += $width;
		}

		
		// linha da tabela
		foreach($datas AS $row => $data) {
			$this->page = $currpage;
			//linha horizontal de cima
		if($border)
			$this->Line($l,$h,$fullwidth+$l,$h);
				foreach($data AS $col => $txt) {
				$this->page = $currpage;

				if($this->xStart)
				{
					$l=$this->xStart;
					$this->xStart=null;
				}			
				
				$this->SetXY($l,$h);
				//imprime a multicell
				
			 if(!$this->tabletitlesfont)
				{
					$fontTitle = array(0=>array('font'=>array ('font'=>'Arial','destaque'=>'','tamanho'=>'8')));
				}
				else
				{
					$fontTitle = array(0=>array('font'=>$this->tabletitlesfont));
				}
				//pega dados da fonte
		        $family=$this->FontFamily;
				$style=$this->FontStyle.($this->underline ? 'U' : '');
				$size=$this->FontSizePt;
				$this->Linha($fontTitle);
				if(!empty($this->tablestyles))
				{				
	       			$this->SetFont($family,$this->tablestyles[$col],$size);					
				}
				
				
				$this->MultiCell($this->tablewidths[$col],$lineheight,$txt,0,$this->tablealigns[$col]);
				
				//seta a fonte usada antes 
	       		$this->SetFont($family,$style,$size);
	       		
	       		
				$l += $this->tablewidths[$col];

				if(!isset($tmpheight[$row.'-'.$this->page]))
				$tmpheight[$row.'-'.$this->page]=0;

				if($tmpheight[$row.'-'.$this->page] < $this->GetY()) {
					$tmpheight[$row.'-'.$this->page] = $this->GetY();
				}

		
				
				if($this->page >= $maxpage)
					$maxpage = $this->page;
			}

			// pega a maior altura da ultima pagina usada
			$h = $tmpheight[$row.'-'.$maxpage];
									
	
			
		   //inicia na margem esquerda
			$l = $this->lMargin;
			// define a pagina atal como sendo a m�xima ja impressa
			$currpage = $maxpage;
		}
		$this->page = $maxpage;
		//linha horizontal de baixo
		if($border)
			$this->Line($l,$h,$fullwidth+$l,$h);

		//�ltima posi��o do y
		if($retornaLinha)
		{
			$this->y=$h-$lineheight; 
		}
		else
		{
			$this->y=$h;
		}
		for($i = $startpage; $i <= $maxpage; $i++) {
			$this->page = $i;
			$l = $this->lMargin;
			$t  = ($i == $startpage) ? $startheight : $this->maxHeader;
			$lh = ($i == $maxpage)   ? $h : $this->h-$this->bMargin-$lineheight+1;
			//linha vertical esquerda
			if($border)
				$this->Line($l,$t,$l,$lh);
			foreach($this->tablewidths AS $width) {
				$l += $width;

					//linha vertical direita
					if($border)
						$this->Line($l,$t,$l,$lh);


			}
		}

		//$this->maxLine = $lh;		
		//$this->maxPage = $maxpage;	
		$this->page = $maxpage;

	}

	//resolve problemas de limpagem de nova p�gia qando j� exite e rodap� e cabelho
	function _beginpage($orientation) {
		$this->page++;
		if(!isset($this->pages[$this->page])){
			$this->pages[$this->page]='';
		}else{
			$this->tMargin=$this->maxHeader;
		}
		$this->state=2;
		$this->x=$this->lMargin;
		$this->y=$this->tMargin;
		$this->lasth=0;
		$this->FontFamily='';
		//Page orientation
		if(!$orientation)
			$orientation=$this->DefOrientation;
		else
		{
			$orientation=strtoupper($orientation{0});
			if($orientation!=$this->DefOrientation)
				$this->OrientationChanges[$this->page]=true;
		}
		if($orientation!=$this->CurOrientation)
		{
			//Change orientation
			if($orientation=='P')
			{
				$this->wPt=$this->fwPt;
				$this->hPt=$this->fhPt;
				$this->w=$this->fw;
				$this->h=$this->fh;
			}
			else
			{
				$this->wPt=$this->fhPt;
				$this->hPt=$this->fwPt;
				$this->w=$this->fh;
				$this->h=$this->fw;
			}
			$this->PageBreakTrigger=$this->h-$this->bMargin;
			$this->CurOrientation=$orientation;
		}
	}

	
	
	
	#################################################   FUN��ES PARA QUEBRAS AUTOM�TICAS NOS RELAT�RIOS - ENEDELSON 26/01/2009		
	
	function printSubFilters($noPrint=array())
	{		
		### -> monta array com as os filtros selecionados no formul�rio e mostra no subt�tulo		
		foreach($this->breaksOptions as $breakId=>$breakValue)
		{
			if($breakValue['filter'])
			{
				$delPrint = array();
				if(!empty($noPrint))
				{
					$delPrint = array_flip($noPrint);
				}				
				if(!array_key_exists($breakId, $delPrint))
				{
					$this->breaksFilters[$breakId]['label'] = $breakValue['label'];     
								
					if(isset($this->dataSet[0][0][$breakValue['field'].'_sigla'])  && isset($this->dataSet[0][0][$breakValue['field']]))
					{
						$this->breaksFilters[$breakId]['content'] = $this->dataSet[0][0][$breakValue['field'].'_sigla'].' - '.$this->dataSet[0][0][$breakValue['field']];
					}
					else
					{							
						if(isset($this->dataSet[0][0][$breakValue['field']]))
						{
							$this->breaksFilters[$breakId]['content'] =  $this->dataSet[0][0][$breakValue['field']];
						}
						else
						{
							$this->breaksFilters[$breakId]['content'] = null;
						}							
					}																		
				}							  				
			}				
		}	
		
		### -> Imprime os fltros no subtitulo
		if(!empty($this->breaksFilters))
		{		
     	 	$family=$this->FontFamily;
			$style=$this->FontStyle.($this->underline ? 'U' : '');
			$size=$this->FontSizePt;
			$this->sub_titulo['font_filters']  = array('font'=>array ('font'=>'Arial','destaque'=>'','tamanho'=>'10'));
			foreach($this->breaksFilters as $keyFilter=>$valueSubtitle){
			 		$this->sub_titulo[$keyFilter]  = array('celula'=>array ('x'=>'0','y'=>'5','texto'=>$valueSubtitle['label'].' '.$valueSubtitle['content'],'borda'=>'0','ln'=>'1','alinhamento'=>'L'));
			}
			$this->sub_titulo['font_filtersLast']  = array('font'=>array ('font'=>$family,'destaque'=>$style,'tamanho'=>$size));													
		}					
	}
	

	function printBreaksGroup($noPrint=array())
	{
		###-> Monta array de quebras
		if(empty($this->breaksFilters))
		{
			$this->breaksFilters = array();
		}					
		foreach($this->breaksOptions as $keyOption=>$valueOption)
		{
			if(!empty($noPrint))
			{
				$arrayNoPrint = array_merge($this->breaksFilters,array_flip($noPrint));
			}
			else
			{
				$arrayNoPrint = $this->breaksFilters;
			}
			if(!array_key_exists($keyOption, $arrayNoPrint))
			{
				$valueOption['value'] = 0;	
				$this->breaksGroup[$keyOption] = $valueOption;
			}
		}
	
		if(!empty($this->breaksGroup))
			$this->breaksGroup = array_reverse($this->breaksGroup);
	}
	
	function printDataSet($border=0,$heightLine = 5)
	{
		
		// labels que ser�o impressas nas linhas de totais
		$this->labelsTotal = array_flip($this->labelsTotal);
		foreach($this->labelsTotal as $idLabel=>$valueLabel){
			$this->labelsTotal[$idLabel] = null;
		}
		
		$codigoItem = 0;	
		###-> Monta array com os dados a serem impressos em cada loop			
		if(!$this->breakItemTitles)
	    {
	     $this->breakItemTitles = array();
	    }
	    $arrayItem = array_merge($this->breakItemTitles,$this->breakItemColuns);	
	    
	    $arrayTypesColum = array();
	    foreach($arrayItem as $keyIdNumer=>$valueTypeColum)
	    {
	    	$arrayTypesColum[$valueTypeColum] = $this->breakItemTypes[$keyIdNumer];
	    }
	    

	    
	    $infoItemHide = array();   
	    foreach($this->breakItemTitles as $infoItemValue)
		{
			$infoItemHide[$infoItemValue] = null;				    	   			    	
		}		    
		$this->positionMaxLine = $this->GetY();	
		$this->positionMaxPage = $positionStartPageItem = $this->getCurPage();
			
		###-> array de acumulador	#####################################################################################
		$breaksGroupTotal = array();
		$arrayCount = array();
		$arrayTotalsItems = array();
		if(!empty($this->breakItemTotals))
		{
			$arrayTotalsItems = array_flip($this->breakItemTotals);
			if($this->breakItemOperation && !empty($this->breakItemValues))
			{
				$array_values = array();
				$arrayValuesId = array_flip($this->breakItemValues);
				foreach($arrayTotalsItems as $keyTotalItem=>$valueTotalItem)
				{
					if(array_key_exists($keyTotalItem, $arrayValuesId))
					{
						$array_values["totvalue_{$keyTotalItem}"] = 0;
					}
				}
				$arrayItems = array_merge($arrayTotalsItems,$array_values);

				$arrayTotalsItems = $arrayItems;
			}	
		}		
		
			
		foreach($this->breakItemTypes as $typeKey =>$valueType)
		{
			if($valueType == 'number' || $valueType =='value' || $valueType =='percent' || $valueType =='integer')
			{
				if(isset($arrayItem[$typeKey]))
				{
					if(array_key_exists($arrayItem[$typeKey], $arrayTotalsItems))
					{
						$arrayCount[$arrayItem[$typeKey]] = 0;
					}
					if(array_key_exists('totvalue_'.$arrayItem[$typeKey], $arrayTotalsItems))
					{
						$arrayCount['totvalue_'.$arrayItem[$typeKey]] = 0;
					}
				}
			}	
		}		

		###->controle de acumula��o para exibi��o de colunas de totais com labels e valores espec�ficos
		if($this->breakTotalItemFields)
		{	
			foreach($this->breakTotalItemFields as $keyT=>$valueT)
			{
				$arrayCount['totitem_'.$valueT] = 0;			
			}	
		}
	
		
		###->controle de acumula��o para exibi��o de colunas de totais com labels e valores espec�ficos das quebras
		if($this->breakTotalFields)
		{	
			foreach($this->breakTotalFields as $keyT=>$valueT)
			{
				$arrayCount['totbreak_'.$valueT] = 0;			
			}	
		}

		
		$this->breakItemTotals = array();
		$this->breakItemTotals = $arrayCount;
		$contTotalGeral = $this->breakItemTotals;
		 
		if(empty($this->breaksGroup)){
			$this->breaksGroup = array();
		}
		foreach($this->breaksGroup as $groupKey =>$valueGroup)
		{
			$breaksGroupTotal[$groupKey] = $this->breakItemTotals;
		}	
		$breaksGroupTotal['total_geral'] = $contTotalGeral;	
		
		$this->breakGroupTotals = $breaksGroupTotal;	
		
		## retira total de uma determinada quebra para n�o exibir
		foreach($this->noBreakGroupTotals as $nototallabel){		
			 if (array_key_exists($nototallabel, $this->breakGroupTotals)) {
			 	unset($this->breakGroupTotals[$nototallabel]);   	
	   		}
		}

		### -> Linha de totais do item	
		$this->lineTotals = array();
		foreach($arrayItem as $valueId)
		{
			$this->lineTotals[$valueId] = null;	
		}
		
	
		
		###-> varre o vetor, imprime linhas do relat�rio ##################################################################
    	foreach($this->dataSet as $key=>$value){	 	
    		if(!empty($this->operationItem)){
    			
    			foreach($this->operationItem as $keyOp=>$ColOp){

    					 
    				switch($ColOp[1])
					{																						
						case "+";								
						$value[0][$keyOp] = $value[0][$ColOp[0]]+$value[0][$ColOp[2]];
						break;																		
						case "-";
						$value[0][$keyOp] = $value[0][$ColOp[0]]-$value[0][$ColOp[2]];
						break;
						case "*";
						$value[0][$keyOp] = $value[0][$ColOp[0]]*$value[0][$ColOp[2]];
						break;	
						case "/";
						if(!$value[0][$ColOp[2]]){
							$value[0][$keyOp] = 0;
						}else{
							$value[0][$keyOp] = $value[0][$ColOp[0]]/$value[0][$ColOp[2]];
						}
						break;			
					}    					
	    				
    			}
    			
    		}

    		// total do item
    		if($this->breakItemControl)
    		{
    			if(($codigoItem || $this->haveBreak) && ($codigoItem != $value[0][$this->breakItemControl]))
				{			
					$this->printTotalItem($value,$arrayTypesColum,$heightLine,$border);
				}
    		}
    		//atualiza label do total de item
    	    foreach($this->labelsTotal as $idLab=>$valueLab){
    	    	$this->labelsTotal[$idLab]=$value[0][$idLab];
    	    }
    		
    		###->Imprime as quebras definidas
			$this->setMaxPrint();			
		    $this->printBreakTotals($value,$heightLine,$border,$codigoItem);
		    $this->getMaxPrint();
				  		    
    		### -> Imprime/oculta colunas por coluna do item de controle
			if($this->breakItemControl)	
			{													   				
			    if($codigoItem != $value[0][$this->breakItemControl] || $positionStartPageItem != $this->getCurPage() || $this->haveBreak)
				{	   		   		
					if(!$this->hideItemControl)
					{
						$this->setMaxPrint();  		   	
			   			$this->printBreakItemControl($value,$heightLine, $border,$codigoItem,$positionStartPageItem);
			   			$this->getMaxPrint();
					}
				}
			}	    
		    
			if(isset($value[0][$this->breakItemControl]))
			{
				$codigoItem = $value[0][$this->breakItemControl];
			}
			
    		### -> incrementa totais do item de controle					
			foreach($this->breakItemTotals as $keyIncrement=>$valueIncrement)
			{
				if(isset($value[0][$keyIncrement]))
				{
			
					if(isset($this->operationsTotalItem[$keyIncrement]))
					{
						$strOperation = 0;
						
						foreach($this->operationsTotalItem[$keyIncrement] as $keyOperation=>$valueOperation)
						{							
															
								if($keyOperation%2 != 0)
							    {								
									switch($valueOperation)
									{																						
										case "+";								
										$strOperation += $value[0][$this->operationsTotalItem[$keyIncrement][$keyOperation+1]];
										break;																		
										case "-";
										$strOperation -= $value[0][$this->operationsTotalItem[$keyIncrement][$keyOperation+1]];
										break;
										case "*";
										$strOperation *= $value[0][$this->operationsTotalItem[$keyIncrement][$keyOperation+1]];
										break;	
										case "/";
											if($value[0][$this->operationsTotalItem[$keyIncrement][$keyOperation+1]]){
												$strOperation /= $value[0][$this->operationsTotalItem[$keyIncrement][$keyOperation+1]];
											}else{
												$strOperation = 0;
											}
										break;			
									}
							   }
							   elseif($keyOperation==0)
							   {
							   		$strOperation = $value[0][$valueOperation];
							   }

							
						}
					
						$this->breakItemTotals[$keyIncrement] += $strOperation;
						$valueTotalGroup = $strOperation;								
					}elseif(array_key_exists($keyIncrement, array_flip($this->removeIncrementoItem))){							
						$this->breakItemTotals[$keyIncrement]= $value[0][$keyIncrement];
					}
					else{
						$this->breakItemTotals[$keyIncrement] += $value[0][$keyIncrement];
					}
					
					
					if(isset($this->breakItemTotals['totvalue_'.$keyIncrement]) && isset($value[0][$this->breakItemOperation]))
					{	
						$this->breakItemTotals['totvalue_'.$keyIncrement] += ($value[0][$keyIncrement]*$value[0][$this->breakItemOperation]);
					}			
				}
				
				if(substr($keyIncrement,0,8) =='totitem_' && isset($value[0][substr($keyIncrement,8)]))
				{
					$this->breakItemTotals[$keyIncrement] += $value[0][substr($keyIncrement,8)];
				}
				
				
			}

    		### -> incrementa totais das quebras					
			foreach($this->breakGroupTotals as $keyIncrementGroup=>$valueIncrementGroup)
			{				
				foreach($valueIncrementGroup as $keyIdGroup=>$valueIdGroup)
				{
					if(isset($value[0][$keyIdGroup]))
					{
						if(isset($valueTotalGroup))
						{
							$this->breakGroupTotals[$keyIncrementGroup][$keyIdGroup] +=	$valueTotalGroup;
						}
						else
						{
							$this->breakGroupTotals[$keyIncrementGroup][$keyIdGroup] += $value[0][$keyIdGroup];	
						}
			
					}	

					if(is_array($this->breakTotalFields) && !empty($this->breakTotalFields))
					{
					
						if(substr($keyIdGroup,0,9) =='totbreak_' && isset($value[0][substr($keyIdGroup,9)]))
						{
							$this->breakGroupTotals[$keyIncrementGroup][$keyIdGroup] += $value[0][substr($keyIdGroup,9)];
						}
					
					}												
					
				}			
			}					
			
	
			###-> Imprime linha de item		
			
			$conteudoItem=null;		
			$keyColun = 0;
			foreach($arrayItem as $valueItem)					
			{
				$contentColun = $value[0][$valueItem];
				if(array_key_exists($valueItem, $infoItemHide))
				{
					$contentColun = $infoItemHide[$valueItem];
				}					
				if(isset($this->breakItemTypes[$keyColun]))
				{						
					switch($this->breakItemTypes[$keyColun])
					{						
						case "text";
							$conteudoItem[0][$keyColun]= $contentColun;
						break;
						
						case "number";
						
							if(!is_null($contentColun))
							{
								$conteudoItem[0][$keyColun] = number_format($contentColun,$_SESSION['Login']['Cliente']['casa_decimal_quantidade'],',','.');							
								//formata n�meros negativos
								if(substr($conteudoItem[0][$keyColun],0,1)=='-')
								{
									$conteudoItem[0][$keyColun] = "(".substr($conteudoItem[0][$keyColun],1).")";
								}					
							
							}
							else
							{
								if ( $this->printZeros ){
									$conteudoItem[0][$keyColun] = number_format(0,$_SESSION['Login']['Cliente']['casa_decimal_quantidade'],',','.');
								}else{
									if($this->detailFormat){
										$conteudoItem[0][$keyColun] = '-';
									}else{
										$conteudoItem[0][$keyColun] = '';
									}
								}
							}
						break;
						case "integer";
						
							if($contentColun != null)
							{
								$conteudoItem[0][$keyColun] = number_format($contentColun,0,',','.');							
								//formata n�meros negativos
								if(substr($conteudoItem[0][$keyColun],0,1)=='-')
								{
									$conteudoItem[0][$keyColun] = "(".substr($conteudoItem[0][$keyColun],1).")";
								}					
							
							}
							else
							{
							if ( $this->printZeros  ){
									$conteudoItem[0][$keyColun] = number_format(0,$_SESSION['Login']['Cliente']['casa_decimal_quantidade'],',','.');
								}else{
									if($this->detailFormat){
										$conteudoItem[0][$keyColun] = '-';
									}else{
										$conteudoItem[0][$keyColun] = '';
									}
								}
								
							}
						break;
						case "value";
							if($contentColun != null)
							{					
								$conteudoItem[0][$keyColun]= number_format($contentColun,$_SESSION['Login']['Cliente']['casa_decimal_valor'],',','.');
								//formata n�meros negativos
								if(substr($conteudoItem[0][$keyColun],0,1)=='-')
								{
									$conteudoItem[0][$keyColun] = "(".substr($conteudoItem[0][$keyColun],1).")";
								}							
							
							}
							else
							{
							if ( $this->printZeros  ){
									$conteudoItem[0][$keyColun] = number_format(0,$_SESSION['Login']['Cliente']['casa_decimal_valor'],',','.');
								}else{
									if($this->detailFormat){
										$conteudoItem[0][$keyColun] = '-';
									}else{
										$conteudoItem[0][$keyColun] = '';
									}
								}
							}
							
							break;
							
						case "percent";
							if($contentColun != null)
							{					
								$conteudoItem[0][$keyColun]= number_format($contentColun*100,2,',','.').'%';
							}
							else
							{
								if($this->detailFormat){
										$conteudoItem[0][$keyColun] = '-';
								}else{
										$conteudoItem[0][$keyColun] = '';
								}
							}
							
						break;	
												
						
						case "date";
							$data_colun = null;
							if($value[0][$valueItem])	{$data_colun = date('d/m/Y', strtotime($contentColun));}			
							$conteudoItem[0][$keyColun]= $data_colun;
						break;	
						case "date_time";
							$data_colun = null;
							if($value[0][$valueItem])	{$data_colun = date('d/m/Y H:i:s', strtotime($contentColun));}			
							$conteudoItem[0][$keyColun]= $data_colun;
						break;		
												
						case "DDMM";
							$data_colun = null;
							if($value[0][$valueItem])	{$data_colun = date('d/m', strtotime($contentColun));}			
							$conteudoItem[0][$keyColun]= $data_colun;
						break;									
					}
				}
				else
				{
					$conteudoItem[0][$keyColun]= $contentColun;
				}				
				$keyColun++;
			}		
			$positionStartPageItem = $this->getCurPage();		
			$this->SetFont('Arial','',8);		

			

			if(!$this->hideItemControl)
			{
				$this->tablecontents($conteudoItem, $heightLine, $border,true);	
			}
							
    		if($this->GetY()+$heightLine >= $this->PageBreakTrigger)
			{
				$this->AddPage();
			}
			$this->getMaxPrint();
    	}    
    	// �ltimo total do item
    	if($this->breakItemControl)
    	{
				$this->printTotalItem($value,$arrayTypesColum,$heightLine,$border);
    	} 	
    	$this->setMaxPrint();
    	$this->printTotalsBreak('total_geral',$heightLine,$border,$codigoItem);
  		$this->getMaxPrint();   	
	}	

	function printTotalItem($value,$arrayTypesColum,$heightLine,$border)
	{							
		### -> linha de totais	do item
		$this->setMaxPrint();				
		$contType = 0;
		$arrayContentsTotals = $this->breakItemTotals;
		
	
		//opera��o especificada para a linha de total do item
		foreach($this->operacaoTotalItem as $itemKeyTotal=>$valueItemTotal){
	    	switch($valueItemTotal[1])
					{																						
						case "+";	
							$this->breakItemTotals[$itemKeyTotal] = $this->breakItemTotals[$valueItemTotal[0]]+$this->breakItemTotals[$valueItemTotal[2]];
						break;																		
						case "-";
							$this->breakItemTotals[$itemKeyTotal] = $this->breakItemTotals[$valueItemTotal[0]]-$this->breakItemTotals[$valueItemTotal[2]];
						break;																		

						case "*";
							$this->breakItemTotals[$itemKeyTotal] = $this->breakItemTotals[$valueItemTotal[0]]*$this->breakItemTotals[$valueItemTotal[2]];
						break;																		

						case "/";
						if(!$this->breakItemTotals[$valueItemTotal[2]]){
							$this->breakItemTotals[$itemKeyTotal] = 0;
						}else{
							$this->breakItemTotals[$itemKeyTotal] = $this->breakItemTotals[$valueItemTotal[0]]/$this->breakItemTotals[$valueItemTotal[2]];	
						}
						break;			
				} 							
			
		}

		foreach($this->breakItemTotals as $keyIncrement=>$valueIncrement)
		{
			if(isset($arrayTypesColum[$keyIncrement]))
			{
				if($arrayTypesColum[$keyIncrement] == 'number')
				{
				 $this->lineTotals[$keyIncrement] = number_format($this->breakItemTotals[$keyIncrement],$_SESSION['Login']['Cliente']['casa_decimal_quantidade'],',','.');
				}
				if($arrayTypesColum[$keyIncrement] == 'integer')
				{
				 $this->lineTotals[$keyIncrement] = number_format($this->breakItemTotals[$keyIncrement],0,',','.');
				}
				if($arrayTypesColum[$keyIncrement] == 'value')
				{
				 $this->lineTotals[$keyIncrement] = number_format($this->breakItemTotals[$keyIncrement],$_SESSION['Login']['Cliente']['casa_decimal_valor'],',','.');
				}
				if($arrayTypesColum[$keyIncrement] == 'percent')
				{
				 $this->lineTotals[$keyIncrement] = number_format($this->breakItemTotals[$keyIncrement]*100,2,',','.').'%';
				}
				$this->breakItemTotals[$keyIncrement] = 0;
			}
			else
			{
				if(isset($this->breakItemTotals[$keyIncrement]))
				{
					$arrayTotDes = explode('_',$keyIncrement);
					if($arrayTotDes[0]=='totvalue')
					{
						 $this->lineTotalsDual[$keyIncrement] = number_format($this->breakItemTotals[$keyIncrement],$_SESSION['Login']['Cliente']['casa_decimal_'.$this->decimalItemOperation],',','.');						 							 
						 $this->breakItemTotals[$keyIncrement] = 0;
					}
					elseif($arrayTotDes[0]=='totitem')
					{						
						 $this->lineTotalsItem[$keyIncrement] = $this->breakItemTotals[$keyIncrement];	
						 $this->breakItemTotals[$keyIncrement] = 0;
					}
				}
			}
			$contType++;
		}			
			
		if($this->printTotalsItems){			
				$contentTotals = null;
				$contColumtotal = 0;
				foreach($this->lineTotals as $keyColumtotal=>$valueLineTotals)
				{
					
				
					//formata n�meros negativos
					if(substr($valueLineTotals,0,1)=='-')
					{
						$valueLineTotals = "(".substr($valueLineTotals,1).")";
					}
					if(array_key_exists($keyColumtotal, $this->labelsTotal) && !$valueLineTotals){
						$valueLineTotals = $this->labelsTotal[$keyColumtotal];
					}
					
					$contentTotals[0][$contColumtotal] = $valueLineTotals;
						
						
					if(isset($this->lineTotalsDual['totvalue_'.$keyColumtotal]))
					{
						$contentTotalsDual[0][$contColumtotal] = $this->lineTotalsDual['totvalue_'.$keyColumtotal];
					}
					else
					{
						$contentTotalsDual[0][$contColumtotal] = null;
					}										
					
					$contColumtotal++;
				}
				
				

				// calcula a posi��o que ser� impressa a palavra total
				$this->tamCellTotal = 0;
				foreach($contentTotals[0] as $keyT=>$valueT){
					if($valueT == null)
					{
						$this->tamCellTotal += $this->tablewidths[$keyT];
					}
					else
					{
						break;
					}
				}		

				
				
				$this->SetFont('Arial','B',8);
				$this->Cell($this->tamCellTotal,$heightLine,'Total:   ',0,0,'R');		
				$this->tablecontents($contentTotals, $heightLine,$border,true);
				$this->SetFont('Arial','',8);
				$this->getMaxPrint();				
				if(!empty($contentTotalsDual) && !empty($this->breakItemValues))
				{
					//imprime 2� linha de total com os valores dos items
					$this->setMaxPrint();
					$this->SetFont('Arial','B',8);
					$this->tamCellTotal = 0;
					foreach($contentTotalsDual[0] as $keyTD=>$valueTD){
						if(!$valueTD)
						{
							$this->tamCellTotal += $this->tablewidths[$keyTD];
						}
						else
						{
							break;
						}
					}
					if($this->labelItemOperation)
					{
						$this->Cell($this->tamCellTotal,$heightLine,$this->labelItemOperation,0,0,'R');
					}
					else
					{
						$this->Cell($this->tamCellTotal,$heightLine,'Valor: ',0,0,'R');
					}
					$this->tablecontents($contentTotalsDual, $heightLine,$border,true);
					$this->SetFont('Arial','',8);
					$this->getMaxPrint();
			 }
		}	
		
		
		if($this->breakTotalItemColums)
		{
			$contentsLabels[0] = null;
			$contentsValues[0] = null;
			$contColum = 0;
			
			foreach($this->breakTotalItemLabels as $keyT=>$valueT)
			{
				$contentsLabels[0][$contColum] = $valueT;
				$valueTotItem = null;
				$valueColum = null;
				if(isset($this->breakTotalItemFields[$contColum]))
				{
					if(isset($this->lineTotalsItem['totitem_'.$this->breakTotalItemFields[$contColum]]))
					{
						$valueColum = $this->lineTotalsItem['totitem_'.$this->breakTotalItemFields[$contColum]];
					}
				}
				if(isset($this->breakTotalItemOperations[$contColum][0]))
				{
					switch($this->breakTotalItemOperations[$contColum][0])
					{	
						case "result-operation-result";
						
							switch($this->breakTotalItemOperations[$contColum][2])
							{									
								case "/";
									$valueColum = $arrayContentsTotals['totitem_'.$this->breakTotalItemOperations[$contColum][1]]/$arrayContentsTotals['totitem_'.$this->breakTotalItemOperations[$contColum][3]];												
								break;
								
								case "*";
									$valueColum = $arrayContentsTotals['totitem_'.$this->breakTotalItemOperations[$contColum][1]]*$arrayContentsTotals['totitem_'.$this->breakTotalItemOperations[$contColum][3]];												
								break;
																
								case "+";
									$valueColum = $arrayContentsTotals['totitem_'.$this->breakTotalItemOperations[$contColum][1]]+$arrayContentsTotals['totitem_'.$this->breakTotalItemOperations[$contColum][3]];												
								break;
								
								case "-";
									$valueColum = $arrayContentsTotals['totitem_'.$this->breakTotalItemOperations[$contColum][1]]-$arrayContentsTotals['totitem_'.$this->breakTotalItemOperations[$contColum][3]];												
								break;									
							}
							
						break;
						
						case "result";							
							$valueColum = $arrayContentsTotals['totitem_'.$this->breakTotalItemOperations[$contColum][1]];												
						break;
						
						case "text";
							$valueColum = $this->breakTotalItemOperations[$contColum][1];	
						break;
						
					}										
				}
				
				switch($this->breakTotalItemTypes[$contColum])
				{						
					case "text";
						$valueTotItem = $valueColum;
						
					break;
					
					case "number";
							$valueTotItem = number_format($valueColum,$_SESSION['Login']['Cliente']['casa_decimal_quantidade'],',','.');
							
					break;
					case "integer";
							$valueTotItem = number_format($valueColum,0,',','.');
							
					break;
					case "value";			
							$valueTotItem = number_format($valueColum,$_SESSION['Login']['Cliente']['casa_decimal_valor'],',','.');					
					break;
						
					case "percent";
							$valueTotItem = number_format($valueColum*100,2,',','.').'%';					
												
					break;									
				}					
				
			
			$contentsValues[0][$contColum] = $valueTotItem;				
			$contColum++;								
			}	
			
		    $this->setMaxPrint();
		    $this->Ln($heightLine);
			$this->SetFont('Arial','B',8);
			$withstitlesAnt = $this->tablewidths;
			$alignsAnt = $this->tablealigns;
			$this->Write($heightLine,' ');
			$this->tablewidths = $this->breakTotalItemColums;
			$this->tablealigns = $this->breakTotalItemAlings;
			$this->tablecontents($contentsLabels, $heightLine, $border);
			$this->tablewidths = $withstitlesAnt;
			$this->tablealigns = $alignsAnt;
			$this->getMaxPrint();				
	   		$this->setMaxPrint();
	   		$this->Write($heightLine,' ');
			$this->SetFont('Arial','B',8);						
			$this->tablewidths = $this->breakTotalItemColums;
			$this->tablealigns = $this->breakTotalItemAlings;				
			$this->tablecontents($contentsValues, $heightLine, $border);
			$this->tablewidths = $withstitlesAnt;
			$this->tablealigns = $alignsAnt;
			$this->getMaxPrint();			
		}		
	}
	
	function printBreakItemControl($value,$heightLine, $border,$codItem,$positionStartPageItem)
	{		
		$this->setMaxPrint();
		if(!$this->haveBreak && $this->breakItemLine && $codItem && ($positionStartPageItem == $this->getCurPage() || $codItem != $value[0][$this->breakItemControl]))
		{
					$this->Cell(0,$heightLine,null,'B',1);
		}
		$this->getMaxPrint();
		
		$positionStarLine  = $this->GetY();
		$positionStartpage  = $this->getCurPage();		
			$this->Write(5,' ');
		if(!empty($this->breakItemDetails) && ($positionStartPageItem == $this->getCurPage() || $codItem != $value[0][$this->breakItemControl]))
		{
			foreach($this->breakItemDetails as $keyInfoItem=>$infoItemValue)
	   	 	{
	   	 		$conteudoShow = null;
	   	 		for($i=0;$i<=$keyInfoItem;$i++)
	   	 		{
	   	 			$conteudoShow[0][$i] = null;
					$contentLabel = $value[0][$infoItemValue];
					switch($this->breakItemDetailsTypes[$i])
					{
						case "text";
							$contentLabel = $value[0][$infoItemValue];
						break;

						case "number";								
							$contentLabel = number_format($value[0][$infoItemValue],$_SESSION['Login']['Cliente']['casa_decimal_quantidade'],',','.');
							//formata n�meros negativos
							if(substr($contentLabel,0,1)=='-')
							{
								$contentLabel = "(".substr($contentLabel,1).")";
							}
						
						break;
						
						case "integer";								
							$contentLabel = number_format($value[0][$infoItemValue],0,',','.');
							//formata n�meros negativos
							if(substr($contentLabel,0,1)=='-')
							{
								$contentLabel = "(".substr($contentLabel,1).")";
							}
						
						break;

						case "value";
							$contentLabel = number_format($value[0][$infoItemValue],$_SESSION['Login']['Cliente']['casa_decimal_valor'],',','.');
							//formata n�meros negativos
							if(substr($contentLabel,0,1)=='-')
							{
								$contentLabel = "(".substr($contentLabel,1).")";
							}							
						break;
						
						case "percent";
							$contentLabel = number_format($value[0][$infoItemValue]*100,2,',','.').'%';
							//formata n�meros negativos
							if(substr($contentLabel,0,1)=='-')
							{
								$contentLabel = "(".substr($contentLabel,1).")";
							}
						
						break;						

						case "date";
							$data_colun = null;
							if($value[0][$infoItemValue])	{$data_colun = date('d/m/Y', strtotime($value[0][$infoItemValue]));}
								$contentLabel= $data_colun;
						break;
						case "date_time";
							$data_colun = null;
							if($value[0][$infoItemValue])	{$data_colun = date('d/m/Y H:i:s', strtotime($value[0][$infoItemValue]));}			
							$contentLabel= $data_colun;
						break;	
						case "DDMM";
							$data_colun = null;
							if($value[0][$infoItemValue])	{$data_colun = date('d/m', strtotime($value[0][$infoItemValue]));}
								$contentLabel= $data_colun;
						break;

					}
	   	 			if($i == $keyInfoItem && isset($this->breakItemDetailsLabel[$i]))
				   	{
				   		$conteudoShow[0][$i] = $this->breakItemDetailsLabel[$i].' '.$contentLabel;

				   	}elseif($i == $keyInfoItem)
				   	{
				   		$conteudoShow[0][$i] = $contentLabel;
				   	}
	   	 		}
	   	 		$this->setMaxPrint();
	   	 		$this->page = $positionStartpage;
			    $this->SetY($positionStarLine);
				$this->SetFont('Arial','',8);
				$withstitlesAnt = $this->tablewidths;
				$alignsAnt = $this->tablealigns;
				$this->Write($heightLine,' ');
				$this->tablewidths = $this->breakItemDetailsColums;
				$this->tablealigns = $this->breakItemDetailsAlings;
				$this->tablecontents($conteudoShow, $heightLine, $border,true);
				$this->tablewidths = $withstitlesAnt;
				$this->tablealigns = $alignsAnt;
				$this->getMaxPrint();			
	   	 	}		
		}	
		
		$this->setMaxPrint();			
		$positionStarLine  = $this->GetY();						
		$positionStartpage  = $this->getCurPage();		
		foreach($this->breakItemTitles as $keyInfoItem=>$infoItemValue)
   	 	{

   	 		$conteudoShow = null;
   	 		for($i=0;$i<=$keyInfoItem;$i++)
   	 		{			   	 			
   	 			if($i == $keyInfoItem)
			   	{
			   				   				   		
			   		switch($this->breakItemTypes[$keyInfoItem])
						{												
							case "text";
							 $conteudoShow[0][$i] = $value[0][$infoItemValue];				
							break;
							
							case "number";
								 $conteudoShow[0][$i] = number_format($value[0][$infoItemValue],$_SESSION['Login']['Cliente']['casa_decimal_quantidade'],',','.');							
							break;
							case "integer";
								 $conteudoShow[0][$i] = number_format($value[0][$infoItemValue],0,',','.');							
							break;
							case "percent";
								 $conteudoShow[0][$i] = number_format($value[0][$infoItemValue]*100,2,',','.').'%';							
							break;
														
							case "value";
								 $conteudoShow[0][$i] = number_format($value[0][$infoItemValue],$_SESSION['Login']['Cliente']['casa_decimal_valor'],',','.');
							break;
								
						}		   							   		
			   	}
			   	else
			   	{
			   		$conteudoShow[0][$i] = null;
			   	}
   	 		}
   	 		$this->page = $positionStartpage;
		    $this->SetY($positionStarLine);
			$this->SetFont('Arial','',8);
			$this->tablecontents($conteudoShow, $heightLine, $border,true);		
			$this->getMaxPrint();																
   	 	}					   	 				   	 
   	 	$this->page = $positionStartpage;
		$this->SetY($positionStarLine);	
	}

	function setMaxPrint()
	{
		$this->page = $this->positionMaxPage;	
		$this->SetY($this->positionMaxLine);	
	}
	
	function getMaxPrint()
	{
		if($this->positionMaxPage == $this->getCurPage() && $this->positionMaxLine < $this->GetY() )
		{
			$this->positionMaxLine = $this->GetY();																								
		}
		elseif($this->positionMaxPage < $this->getCurPage())
		{
			$this->positionMaxPage = $this->getCurPage();
			$this->positionMaxLine = $this->GetY();
		}
	}
		
	function printBreakTotals($value,$heightLine,$border,$codigoItem)
	{
		$breakIdLast = null;
		$lineBreak = 0;
		foreach($this->breaksGroup as $keyGroup=>$valueGroup)
		{
			if($valueGroup['value'] != $value[0][$keyGroup])
			{
				$breakIdLast = $keyGroup;
				if($valueGroup['line'])
				{
					$lineBreak = 1;
				}
				
				$this->breaksGroup[$keyGroup]['value'] = $value[0][$keyGroup];				
			}	
			
		}
		$numLinesNextBreak = $heightLine;
		if($breakIdLast && $codigoItem)
		{

			$contBreaks = $this->printTotalsBreak($breakIdLast,$heightLine,$border,$codigoItem);
			if($contBreaks >1 && !$this->spaceGroupBotton)//imprime espa�o quando houver mais de uma quebra e a op��o de espa�o inferior estiver desabilitada
			{
				$this->Cell(0,$heightLine,null,0,1);
			}
			if($this->spaceGroupBotton)
				    //$this->Ln($heightLine); alterado em 30/03/2010 diminuir espaco entre itens e quebras
					$this->Ln(2);
			$numLinesNextBreak = ($contBreaks*$heightLine)+($heightLine*2);						
	
		}	
		if($codigoItem)
		$this->haveBreak = $breakIdLast;			
		####-> imprime novas quebras		
		$this->printBreak($value,$numLinesNextBreak,$breakIdLast,$lineBreak,$heightLine,$codigoItem);				
	}
	
	function printBreak($value,$numLinesNextBreak,$breakIdLast,$lineBreak,$heightLine,$codigoItem)
	{					
			$printSubtitle = false;
			if($this->GetY()+$numLinesNextBreak >= $this->PageBreakTrigger)
			{		
				$printSubtitle = true;
			}
			

			if($lineBreak && !$printSubtitle && $codigoItem)
			{
				$this->Cell(0,0,null,1,1);
			}
			$printBreak = false;
			
			$array_breaks = array();
			if(!empty($this->breaksGroup))
				$array_breaks = array_reverse($this->breaksGroup);
			foreach($array_breaks as $keyPrint=>$valuePrint)
			{
				
				if($breakIdLast == $keyPrint)
				{
					$printBreak = true;
				}
				$content = null;
				if (isset($valuePrint['margin']) and !empty($valuePrint['margin'])){
						$margin = $this->breakWidthLabel + $valuePrint['margin'];	
					} else $margin = $this->breakWidthLabel;
				if(isset($value[0][$valuePrint['field'].'_sigla']) && isset($value[0][$valuePrint['field']]))
				{
					$content = $value[0][$valuePrint['field'].'_sigla'].' - '.$value[0][$valuePrint['field']];
				}
				elseif(isset($value[0][$valuePrint['field']]))
				{
					$content = $value[0][$valuePrint['field']];
				}				
				if($printBreak && !$printSubtitle)
				{
					

					$this->SetFont('Arial','',10);
					$this->Cell($margin,$heightLine,$valuePrint['label'],$this->breakBorderLabel,0,'R');
					$this->SetFont('Arial','B',10);									
					$this->MultiCell(0,$heightLine,$content,$this->breakBorderLabel,'L');
					$this->SetFont('Arial','',8);
					
				}
						
				###-> seta a quebra para o subt�tulo da proxima p�gina
				if (isset($valuePrint['margin']) and !empty($valuePrint['margin'])){
					$this->breaksSubtitles[$keyPrint['id']]['margin'] = $valuePrint['margin'];
				}
				$this->breaksSubtitles[$keyPrint['id']]['label'] = $valuePrint['label'];
				$this->breaksSubtitles[$keyPrint['id']]['value'] = $content;
				$this->breaksSubtitles[$keyPrint['id']]['height'] = $heightLine;
			}
			if($printSubtitle)
			{
				$this->AddPage();
			}
			$this->haveBreak = $printBreak;
			if($printBreak && $this->spaceGroupTop)
				//$this->Ln($heightLine); mudanca em 30/03/2010 - diminuir espa�o entre itens e quebras	
					$this->Ln(0.5);	
				
	}
	
	function printTotalsBreak($breakIdLast,$heightLine,$border,$codigoItem)
	{
	
		if($codigoItem){
			$arrayTotals = array();
			$contBreaks = 0;
		
			foreach($this->breakGroupTotals as $idGroup=>$valueGroup)
			{
				if (!$this->printTotalGeral) {
					if($idGroup == 'total_geral'){
						unset($this->breakGroupTotals['total_geral']);
						continue;
					}
				}
				
				$cntClom = 0;
				foreach($this->lineTotals as $keyColumtotal=>$valueLineTotals)
				{
					if(isset($valueGroup[$keyColumtotal]))
					{						
						switch($this->breakItemTypes[$cntClom])
						{												
							case "text";
								$arrayTotals[$idGroup][$cntClom] = $valueGroup[$keyColumtotal];						
							break;
							
							case "number";
								$arrayTotals[$idGroup][$cntClom] = number_format($valueGroup[$keyColumtotal],$_SESSION['Login']['Cliente']['casa_decimal_quantidade'],',','.');							
							break;
							case "integer";
								$arrayTotals[$idGroup][$cntClom] = number_format($valueGroup[$keyColumtotal],0,',','.');							
							break;
							case "percent";
								$arrayTotals[$idGroup][$cntClom] = number_format($valueGroup[$keyColumtotal]*100,2,',','.').'%';							
							break;
														
							case "value";
								$arrayTotals[$idGroup][$cntClom] = number_format($valueGroup[$keyColumtotal],$_SESSION['Login']['Cliente']['casa_decimal_valor'],',','.');
							break;									
						}																		
						
						###-> n�o imprime colunas espec�ficas de total
						if(is_array($this->printBreaksGroups) && !empty($this->printBreaksGroups))
						{
							if(array_key_exists($keyColumtotal, $this->printBreaksGroups))
							{
								$arrayTotals[$idGroup][$cntClom] = null;
							}
						}
					
					}
					else
					{
						$arrayTotals[$idGroup][$cntClom] = null;
					}
					$cntClom++;
				}				
				//formata n�meros negativos			
				foreach($arrayTotals[$idGroup] as $clTotal=> $vlTotal)
				{
						if(substr($vlTotal,0,1)=='-')
						{
							$vlTotal = substr($vlTotal,1);
							$arrayTotals[$idGroup][$clTotal]= "(".$vlTotal.")";
						}					
				}		
				
				$contentTotal = null;
				$contentTotal[0] = $arrayTotals[$idGroup];
				$this->setMaxPrint();
				$this->SetFont('Arial','B',8);
				$label = null;
				
				if(isset($this->breaksGroup[$idGroup]['labelTotal'])){
					$label = $this->breaksGroup[$idGroup]['labelTotal'];
				}elseif(isset($this->breaksGroup[$idGroup]['label']))
				{								
					$label = $this->breaksGroup[$idGroup]['label'];
				}
				if($idGroup == 'total_geral')
				{
					$label = 'Geral: ';
					$this->Ln($heightLine*$this->spaceGeral);
					$this->getMaxPrint();
					$this->setMaxPrint();
				}
				
				//calcula tamanho da descri��o do total
				$this->tamCellTotal = 0;
				foreach($arrayTotals[$idGroup] as $columIdTotal=> $columTotal)
				{
					if(!$columTotal)
					{
						$this->tamCellTotal +=$this->tablewidths[$columIdTotal];
					}
					else
					{
						break;
					}
				}	

				
				if($this->printBreaksGroups)
				{
					$this->Cell($this->tamCellTotal,$heightLine, (!empty($label)) ? 'Total '.$label : 'Total: ',0,0,'R');			
					$this->tablecontents($contentTotal, $heightLine,$border,true);
				}
				
				############################################################################################## aqui Quebras personalizadas		
				if(is_array($this->breakTotalFields) && !empty($this->breakTotalFields) && $this->printTotalGroups)
				{
	
					if($this->breakTotalColums)
					{
						$contentsLabels[0] = null;
						$contentsValues[0] = null;
						$contColum = 0;
						$arrayContentsTotals = $this->breakGroupTotals;

						foreach($this->breakTotalLabels as $keyT=>$valueT)
						{
							$contentsLabels[0][$contColum] = $valueT;
							$valueTotItem = null;
							$valueColum = null;
							
							if (!$this->printTotalGeral) {
								if($idGroup == 'total_geral'){
									unset($this->breaksGroup['total_geral']);
									continue;
								}
							}				
							
							
							
							if($idGroup =='total_geral'){
								$this->breaksGroup[$idGroup]['label'] = 'Geral: ';
							}
							

							if(isset($this->breakTotalOperations[$contColum][0]))
							{
								
								switch($this->breakTotalOperations[$contColum][0])
								{
									
									case "result-operation-result";
									
										switch($this->breakTotalOperations[$contColum][2])
										{									
											case "/";
												if($arrayContentsTotals[$idGroup]['totbreak_'.$this->breakTotalOperations[$contColum][3]]){
													$valueColum = $arrayContentsTotals[$idGroup]['totbreak_'.$this->breakTotalOperations[$contColum][1]]/$arrayContentsTotals[$idGroup]['totbreak_'.$this->breakTotalOperations[$contColum][3]];																					
												}else{
													$valueColum = 0;
												}
												break;
											
											case "*";
												$valueColum = $arrayContentsTotals[$idGroup]['totbreak_'.$this->breakTotalOperations[$contColum][1]]*$arrayContentsTotals[$idGroup]['totbreak_'.$this->breakTotalOperations[$contColum][3]];												
											break;
																			
											case "+";
												$valueColum = $arrayContentsTotals[$idGroup]['totbreak_'.$this->breakTotalOperations[$contColum][1]]+$arrayContentsTotals[$idGroup]['totbreak_'.$this->breakTotalOperations[$contColum][3]];												
											break;
											
											case "-";
												$valueColum = $arrayContentsTotals[$idGroup]['totbreak_'.$this->breakTotalOperations[$contColum][1]]-$arrayContentsTotals[$idGroup]['totbreak_'.$this->breakTotalOperations[$contColum][3]];												
											break;									
										}
										
									break;
									
									case "result";							
										$valueColum = $arrayContentsTotals[$idGroup]['totbreak_'.$this->breakTotalOperations[$contColum][1]];												
									break;
									
									case "text-label";											
										$valueColum  = $this->breakTotalOperations[$contColum][1].$this->breaksGroup[$idGroup]['label'];														
									break;
																		
									case "text";
										$valueColum = $this->breakTotalOperations[$contColum][1];	
									break;
									

								}										
							}
													
							switch($this->breakTotalTypes[$contColum])
							{						
								case "text";
									$valueTotItem = $valueColum;
									
								break;
								
								case "number";
										$valueTotItem = number_format($valueColum,$_SESSION['Login']['Cliente']['casa_decimal_quantidade'],',','.');
										
								break;
								case "integer";
										$valueTotItem = number_format($valueColum,0,',','.');
										
								break;
								case "value";			
										$valueTotItem = number_format($valueColum,$_SESSION['Login']['Cliente']['casa_decimal_valor'],',','.');					
								break;
									
								case "percent";
										$valueTotItem = number_format($valueColum*100,2,',','.').'%';					
															
								break;									
							}																				
							$contentsValues[0][$contColum] = $valueTotItem;				
							$contColum++;	
						}
						$this->setMaxPrint();
						$this->SetFont('Arial','B',8);						
						$withstitlesAnt = $this->tablewidths;
						$alignsAnt = $this->tablealigns;
						if(!$this->hideItemControl)
						   		 $this->Ln($heightLine);
						if(!$this->noBreakTotalLabels)
						{
							$this->Write($heightLine,' ');
							$this->tablewidths = $this->breakTotalColums;
							$this->tablealigns = $this->breakTotalAlings;
							$this->tablecontents($contentsLabels, $heightLine, $border);
							$this->tablewidths = $withstitlesAnt;
							$this->tablealigns = $alignsAnt;												
						}	
						$this->getMaxPrint();		
				   		$this->setMaxPrint();
				   		$this->Write($heightLine,' ');
						$this->SetFont('Arial','B',8);						
						$this->tablewidths = $this->breakTotalColums;
						$this->tablealigns = $this->breakTotalAlings;				
						$this->tablecontents($contentsValues, $heightLine, $border);
						$this->tablewidths = $withstitlesAnt;
						$this->tablealigns = $alignsAnt;
						$this->getMaxPrint();					
					}		
					
				}
							
				$this->SetFont('Arial','',8);
				$this->getMaxPrint();		
				
				//zerar o total da quebra e break;				
				
				foreach($this->breakGroupTotals[$idGroup] as $keyBreakNow =>$valueBreakNow)
				{
					$this->breakGroupTotals[$idGroup][$keyBreakNow] = 0;
				}
				$contBreaks ++;
				if($breakIdLast == $idGroup)
				{
					break;
				}				
				
				
			}
			return $contBreaks;
		}					
	}
	
	function noPrintTotalsBreak($noPrint=array())
	{		
		$delPrint = array();
		if(!empty($noPrint))
		{
			$delPrint = array_flip($noPrint);
		}
		$this->printBreaksGroups = $delPrint;	
	}
	
	function isPageBreak($h = 0)
	{
		if($this->y+$h>$this->PageBreakTrigger && !$this->InFooter && $this->AcceptPageBreak())
		{
			return true;
		}

		return false;
	}	
}

?>